<?php
declare(strict_types=1);

namespace app\controller\user;

use app\model\DistributionRecord;
use app\model\MerchantDistributionConfig;
use think\facade\Cache;
use app\model\User;
use app\model\UserInviteRecord;

class DistributionController
{
    /**
     * 获取分销概览
     */
    public function overview()
    {
        $merchantId = request()->merchant_id;
        $userId = request()->user_id;

        // 获取分销配置
        $config = MerchantDistributionConfig::getConfig($merchantId);
        if (!$config['enabled']) {
            return json(['code' => 1, 'msg' => '分销功能未开启']);
        }

        // 获取分销统计
        $stats = DistributionRecord::getUserStats($userId, $merchantId);
        
        // 获取下级用户数量
        $level1Count = \app\model\User::where([
            'merchant_id' => $merchantId,
            'parent_id' => $userId
        ])->count();
        
        $level2Count = \app\model\User::where([
            'merchant_id' => $merchantId,
            'parent_id' => function($query) use ($merchantId, $userId) {
                $query->name('user')->where([
                    'merchant_id' => $merchantId,
                    'parent_id' => $userId
                ])->field('id');
            }
        ])->count();

        return json([
            'code' => 0,
            'msg' => 'success',
            'data' => [
                'stats' => $stats,
                'level1_count' => $level1Count,
                'level2_count' => $level2Count,
                'level1_rate' => $config['level1_rate'],
                'level2_rate' => $config['level2_rate']
            ]
        ]);
    }

    /**
     * 获取分销记录
     */
    public function records()
    {
        $merchantId = request()->merchant_id;
        $userId = request()->user_id;
        $status = input('status/d', -1);
        $page = input('page/d', 1);
        $limit = input('limit/d', 20);

        $where = [
            'merchant_id' => $merchantId,
            'user_id' => $userId
        ];
        
        if ($status >= 0) {
            $where['status'] = $status;
        }

        $list = DistributionRecord::where($where)
            ->order('id', 'desc')
            ->paginate([
                'list_rows' => $limit,
                'page' => $page
            ]);

        return json([
            'code' => 0,
            'msg' => 'success',
            'data' => $list
        ]);
    }

    /**
     * 获取邀请码
     */
    public function getInviteCode()
    {
        $merchantId = request()->merchant_id;
        $userId = request()->user_id;
        
        // 生成邀请码
        $inviteCode = md5($merchantId . $userId . time());
        
        // 缓存邀请码
        Cache::set("invite_code:{$inviteCode}", [
            'merchant_id' => $merchantId,
            'user_id' => $userId
        ], 7 * 86400); // 7天有效期
        
        return json([
            'code' => 0,
            'msg' => 'success',
            'data' => [
                'invite_code' => $inviteCode,
                'invite_url' => config('app.h5_url') . '/register?code=' . $inviteCode
            ]
        ]);
    }

    /**
     * 使用邀请码注册
     */
    public function register()
    {
        $inviteCode = input('invite_code');
        if (!$inviteCode) {
            return json(['code' => 1, 'msg' => '邀请码不能为空']);
        }
        
        // 验证邀请码
        $inviteInfo = Cache::get("invite_code:{$inviteCode}");
        if (!$inviteInfo) {
            return json(['code' => 1, 'msg' => '邀请码已过期']);
        }
        
        // 创建用户
        $user = User::create([
            'merchant_id' => $inviteInfo['merchant_id'],
            'parent_id' => $inviteInfo['user_id'],
            // ... 其他用户信息
        ]);
        
        // 记录邀请关系
        UserInviteRecord::create([
            'merchant_id' => $inviteInfo['merchant_id'],
            'inviter_id' => $inviteInfo['user_id'],
            'invitee_id' => $user->id,
            'invite_code' => $inviteCode
        ]);
        
        // 发送通知
        event('UserInvited', [
            'merchant_id' => $inviteInfo['merchant_id'],
            'inviter_id' => $inviteInfo['user_id'],
            'invitee_id' => $user->id
        ]);
        
        return json(['code' => 0, 'msg' => '注册成功']);
    }
} 